package com.kerwin.event;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

public class Main {

    //微任务队列-优先级高
    private static Queue<ScheduleMicrotask> scheduleMicrotasks = new LinkedBlockingQueue<>();
    //事件队列-优先级低
    private static Queue<Timer> timers = new LinkedBlockingQueue<>();

    public static void processAsync(){

        while(!scheduleMicrotasks.isEmpty() || !timers.isEmpty()){
            Task task = null;
            if((task = scheduleMicrotasks.poll()) != null){

            }else if((task = timers.poll()) != null){

            }
            task.run();
        }
    }


    public static void main(String[] args){
        System.out.println("main start!");
        timers.offer(new Timer(){
            @Override
            public void run() {
                System.out.println("timer - event - A");
                scheduleMicrotasks.offer(new ScheduleMicrotask(){
                    @Override
                    public void run() {
                        System.out.println("ScheduleMicrotask - A - in Timer A");
                    }
                });

                scheduleMicrotasks.offer(new ScheduleMicrotask(){
                    @Override
                    public void run() {
                        System.out.println("ScheduleMicrotask - B - in Timer A");
                    }
                });
            }
        });

        scheduleMicrotasks.offer(new ScheduleMicrotask(){
            @Override
            public void run() {
                System.out.println("ScheduleMicrotask - C - in MAIN ");

                timers.offer(new Timer(){
                    @Override
                    public void run() {
                        System.out.println("timer - event - B - in ScheduleMicrotask - C ");
                    }
                });
            }
        });


        System.out.println("main end!");

        processAsync();
    }

}
